extends Control
class_name ChatUI

# 消息类型枚举
enum MessageType {
	USER,
	AI
}

const COLOR_USER_TEXT = Color.WHITE                   # 用户消息文字色
const COLOR_AI_TEXT = Color(0.9, 0.9, 0.9)           # AI消息文字色

# UI控件引用
@export var message_container: VBoxContainer
@export var input_container: HBoxContainer
@export var input_field: TextEdit
@export var send_button: Button
@export var scroll_container: ScrollContainer
@export var abort_button: Button

# 当前AI状态
var ai_thinking = false
var ai_aborted = false

# 当前AI信息
var cur_ai_message: Label = null

func _ready():
	# 设置UI布局
	setup_ui()
	

func setup_ui():
	send_button.pressed.connect(_on_send_pressed)
	abort_button.pressed.connect(_on_abort_pressed)


func add_message(type: MessageType, text: String = ""):
	# 创建消息容器
	var message_box = PanelContainer.new()
	#message_box.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	message_box.size_flags_vertical = Control.SIZE_EXPAND_FILL
	
	# 创建内容容器
	var content = HBoxContainer.new()
	#content.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	content.size_flags_vertical = Control.SIZE_EXPAND_FILL
	message_box.add_child(content)
	

	
	var label = Label.new()
	
	
	
	label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
	label.size_flags_vertical = Control.SIZE_EXPAND_FILL
	#label.clip_text = true
	
	match type:
		MessageType.USER:

			label.add_theme_color_override("font_color", COLOR_USER_TEXT)
			cur_ai_message = null

		MessageType.AI:

			label.add_theme_color_override("font_color", COLOR_AI_TEXT)
			# 设置当前AI对话
			cur_ai_message = label



	content.add_child(label)
	label.text = text

	message_container.add_child(message_box)
	

	
	# 滚动到底部
	await get_tree().process_frame
	scroll_container.scroll_vertical = scroll_container.get_v_scroll_bar().max_value

func show_thinking():
	ai_thinking = true
	ai_aborted = false
	if cur_ai_message != null:
		cur_ai_message.set_text("思考中...")

func show_aborted():
	ai_thinking = false
	ai_aborted = true
	if cur_ai_message != null:
		cur_ai_message.set_text("回复已中断")

	
func reply(content: String):
	if ai_aborted:
		return
	cur_ai_message.set_text(content)
	ai_thinking = false
	ai_aborted = false
	pass
	
func _on_send_pressed():
	if ai_thinking:
		return
	var message = input_field.text.strip_edges()
	if message.is_empty():
		return
	
	# 添加用户消息
	add_message(MessageType.USER, message)
	
	# 清空输入框
	input_field.text = ""
	
	
	# 显示思考状态
	show_thinking()
	
	
	# 如果被中断则不显示回复
	if ai_aborted:
		ai_thinking = false
		return
	
	# 添加AI回复
	ai_thinking = false
	add_message(MessageType.AI)
	show_thinking()
	reply("你好，这是回复")

func _on_abort_pressed():
	if ai_thinking:
		show_aborted()
